package com.czi.webrtctemp

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit

// 信令数据模型
data class SdpExchangeModel(
    val app: String,
    val stream: String,
    val type: String, // "offer" or "answer"
    val sdp: String
)

object SignalingClient {
    private const val TAG = "WebRTC-Signaling"
    private val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(15, TimeUnit.SECONDS)
        .build()

    /**
     * 发送本地SDP并获取远端SDP
     */
    suspend fun exchangeSDP(
        baseUrl: String,
        model: SdpExchangeModel
    ): Result<String> = withContext(Dispatchers.IO) {
        try {
            val url = "${baseUrl}?app=${model.app}&stream=${model.stream}&type=${model.type}"
            val request = Request.Builder()
                .url(url)
                .post(model.sdp.toRequestBody("text/plain".toMediaType()))
                .addHeader("Accept", "application/sdp")
                .build()

            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) {
                    return@withContext Result.failure(Exception("HTTP ${response.code}"))
                }
                response.body?.string()?.let {
                    Result.success(it)
                } ?: Result.failure(Exception("Empty response"))
            }
        } catch (e: Exception) {
            Log.e(TAG, "SDP exchange failed", e)
            Result.failure(e)
        }
    }
}